"""
中间件
"""
import time
from fastapi import Request, Response
from starlette.middleware.base import BaseHTTPMiddleware
from app.core.logger import logger


class APILoggerMiddleware(BaseHTTPMiddleware):
    """API 请求日志中间件"""
    
    async def dispatch(self, request: Request, call_next):
        # 记录请求开始时间
        start_time = time.time()
        
        # 获取请求信息
        method = request.method
        url = str(request.url)
        client_host = request.client.host if request.client else "unknown"
        
        # 记录请求
        logger.info(f"📨 API Request: {method} {url} from {client_host}")
        
        # 处理请求
        try:
            response: Response = await call_next(request)
            
            # 计算处理时间
            process_time = time.time() - start_time
            
            # 记录响应
            logger.info(
                f"📤 API Response: {method} {url} "
                f"status={response.status_code} "
                f"time={process_time:.3f}s"
            )
            
            # 添加处理时间到响应头
            response.headers["X-Process-Time"] = f"{process_time:.3f}"
            
            return response
            
        except Exception as e:
            # 记录异常
            process_time = time.time() - start_time
            logger.error(
                f"❌ API Error: {method} {url} "
                f"error={str(e)} "
                f"time={process_time:.3f}s"
            )
            raise

